<?php
/**
 * Created by PhpStorm.
 * User: ari
 * Date: 12/19/2014
 * Time: 4:02 PM
 */
namespace BC\User\Grant\DB;

use BC\User\Grant\GrantConfig;
use BC\Wallet\Bitcoin\BitcoinAddressLookupTable;
use CPath\Data\Schema\IReadableSchema;
use CPath\Data\Schema\IRepairableSchema;
use CPath\Data\Schema\IWritableSchema;
use CPath\Data\Schema\PDO\AbstractPDOTable;
use PDO;

class GrantDB extends \PDO implements IReadableSchema, IRepairableSchema
{
	const DB = 'grant.sqlite';
	const TABLE_GRANT = 'grant';

	public function __construct($options = null) {
		$path     = GrantConfig::getContentPath(self::DB);
		$username = GrantConfig::$DB_USERNAME;
		$passwd   = GrantConfig::$DB_PASSWORD;

		parent::__construct('sqlite:' . $path, $username, $passwd, $options);
		$this->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
//		$this->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
	}

	/**
	 * Write schema to a writable source
	 * @param IWritableSchema $DB
	 */
	public function writeSchema(IWritableSchema $DB) {
		foreach(
			array(
				new GrantTable(),
				new GrantUserTable(),
		        new BitcoinAddressLookupTable()
			) as $Table) {
			/** @var AbstractPDOTable $Table */
			$Table->writeSchema($DB);
		}
	}

	/**
	 * Attempt to repair a writable schema
	 * @param IWritableSchema $DB
	 * @param \Exception $ex
	 */
	public function repairSchema(IWritableSchema $DB, \Exception $ex) {
		$this->writeSchema($DB);
	}
}